import React, { useState } from 'react'
import { Card, Row, Col, Select, DatePicker, Button, Table, Space, Statistic, Progress } from 'antd'
import { DownloadOutlined, PrinterOutlined, FileExcelOutlined, FilePdfOutlined } from '@ant-design/icons'
import { LineChart, Line, BarChart, Bar, PieChart, Pie, Cell, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts'
import Layout from '../components/Layout/Layout'
import dayjs from 'dayjs'

const { RangePicker } = DatePicker
const { Option } = Select

export default function Reports() {
  const [reportType, setReportType] = useState('energy')
  const [dateRange, setDateRange] = useState([dayjs().subtract(30, 'day'), dayjs()])
  const [loading, setLoading] = useState(false)

  // 模拟数据
  const energyData = [
    { date: '01-01', consumption: 2400, cost: 1200 },
    { date: '01-02', consumption: 2210, cost: 1100 },
    { date: '01-03', consumption: 2290, cost: 1150 },
    { date: '01-04', consumption: 2000, cost: 1000 },
    { date: '01-05', consumption: 2181, cost: 1090 },
    { date: '01-06', consumption: 2500, cost: 1250 },
    { date: '01-07', consumption: 2100, cost: 1050 },
  ]

  const parkingData = [
    { name: 'A区', value: 120, color: '#8884d8' },
    { name: 'B区', value: 98, color: '#82ca9d' },
    { name: 'C区', value: 86, color: '#ffc658' },
    { name: 'D区', value: 67, color: '#ff7300' },
  ]

  const deviceStatusData = [
    { status: '正常', count: 142, color: '#52c41a' },
    { status: '警告', count: 8, color: '#faad14' },
    { status: '故障', count: 3, color: '#ff4d4f' },
    { status: '离线', count: 5, color: '#d9d9d9' },
  ]

  const personnelData = [
    { department: '技术部', total: 25, present: 23, absent: 2 },
    { department: '市场部', total: 18, present: 16, absent: 2 },
    { department: '财务部', total: 12, present: 11, absent: 1 },
    { department: '人事部', total: 8, present: 8, absent: 0 },
    { department: '运营部', total: 15, present: 13, absent: 2 },
  ]

  const handleExport = (format) => {
    setLoading(true)
    setTimeout(() => {
      setLoading(false)
      message.success(`${format}报表导出成功`)
    }, 2000)
  }

  const handlePrint = () => {
    window.print()
  }

  const renderEnergyReport = () => (
    <div>
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="总能耗"
              value={15847.5}
              suffix="kWh"
              valueStyle={{ color: '#3f8600' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="总费用"
              value={7923.75}
              prefix="¥"
              valueStyle={{ color: '#cf1322' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="平均日耗"
              value={2263.9}
              suffix="kWh"
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="节能率"
              value={12.5}
              suffix="%"
              valueStyle={{ color: '#722ed1' }}
            />
          </Card>
        </Col>
      </Row>

      <Row gutter={16}>
        <Col span={12}>
          <Card title="能耗趋势" size="small">
            <ResponsiveContainer width="100%" height={300}>
              <LineChart data={energyData}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="date" />
                <YAxis />
                <Tooltip />
                <Legend />
                <Line type="monotone" dataKey="consumption" stroke="#8884d8" name="能耗(kWh)" />
              </LineChart>
            </ResponsiveContainer>
          </Card>
        </Col>
        <Col span={12}>
          <Card title="费用趋势" size="small">
            <ResponsiveContainer width="100%" height={300}>
              <BarChart data={energyData}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="date" />
                <YAxis />
                <Tooltip />
                <Legend />
                <Bar dataKey="cost" fill="#82ca9d" name="费用(元)" />
              </BarChart>
            </ResponsiveContainer>
          </Card>
        </Col>
      </Row>
    </div>
  )

  const renderParkingReport = () => (
    <div>
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="总车位"
              value={500}
              valueStyle={{ color: '#3f8600' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="已占用"
              value={371}
              valueStyle={{ color: '#cf1322' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="使用率"
              value={74.2}
              suffix="%"
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="今日收入"
              value={15420}
              prefix="¥"
              valueStyle={{ color: '#722ed1' }}
            />
          </Card>
        </Col>
      </Row>

      <Row gutter={16}>
        <Col span={12}>
          <Card title="各区域车位分布" size="small">
            <ResponsiveContainer width="100%" height={300}>
              <PieChart>
                <Pie
                  data={parkingData}
                  cx="50%"
                  cy="50%"
                  labelLine={false}
                  label={({ name, percent }) => `${name} ${(percent * 100).toFixed(0)}%`}
                  outerRadius={80}
                  fill="#8884d8"
                  dataKey="value"
                >
                  {parkingData.map((entry, index) => (
                    <Cell key={`cell-${index}`} fill={entry.color} />
                  ))}
                </Pie>
                <Tooltip />
              </PieChart>
            </ResponsiveContainer>
          </Card>
        </Col>
        <Col span={12}>
          <Card title="车位使用详情" size="small">
            <Table
              dataSource={parkingData.map(item => ({
                ...item,
                total: 125,
                occupied: item.value,
                available: 125 - item.value,
                rate: ((item.value / 125) * 100).toFixed(1)
              }))}
              columns={[
                { title: '区域', dataIndex: 'name', key: 'name' },
                { title: '总数', dataIndex: 'total', key: 'total' },
                { title: '占用', dataIndex: 'occupied', key: 'occupied' },
                { title: '可用', dataIndex: 'available', key: 'available' },
                { 
                  title: '使用率', 
                  key: 'rate',
                  render: (_, record) => (
                    <Progress percent={parseFloat(record.rate)} size="small" />
                  )
                },
              ]}
              pagination={false}
              size="small"
            />
          </Card>
        </Col>
      </Row>
    </div>
  )

  const renderDeviceReport = () => (
    <div>
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="设备总数"
              value={158}
              valueStyle={{ color: '#3f8600' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="在线设备"
              value={142}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="在线率"
              value={89.9}
              suffix="%"
              valueStyle={{ color: '#722ed1' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="故障设备"
              value={3}
              valueStyle={{ color: '#cf1322' }}
            />
          </Card>
        </Col>
      </Row>

      <Row gutter={16}>
        <Col span={12}>
          <Card title="设备状态分布" size="small">
            <ResponsiveContainer width="100%" height={300}>
              <PieChart>
                <Pie
                  data={deviceStatusData}
                  cx="50%"
                  cy="50%"
                  labelLine={false}
                  label={({ name, percent }) => `${name} ${(percent * 100).toFixed(0)}%`}
                  outerRadius={80}
                  fill="#8884d8"
                  dataKey="count"
                >
                  {deviceStatusData.map((entry, index) => (
                    <Cell key={`cell-${index}`} fill={entry.color} />
                  ))}
                </Pie>
                <Tooltip />
              </PieChart>
            </ResponsiveContainer>
          </Card>
        </Col>
        <Col span={12}>
          <Card title="设备状态统计" size="small">
            <Table
              dataSource={deviceStatusData}
              columns={[
                { title: '状态', dataIndex: 'status', key: 'status' },
                { title: '数量', dataIndex: 'count', key: 'count' },
                { 
                  title: '占比', 
                  key: 'percentage',
                  render: (_, record) => {
                    const total = deviceStatusData.reduce((sum, item) => sum + item.count, 0)
                    const percentage = ((record.count / total) * 100).toFixed(1)
                    return `${percentage}%`
                  }
                },
              ]}
              pagination={false}
              size="small"
            />
          </Card>
        </Col>
      </Row>
    </div>
  )

  const renderPersonnelReport = () => (
    <div>
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="总人数"
              value={78}
              valueStyle={{ color: '#3f8600' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="在岗人数"
              value={71}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="出勤率"
              value={91.0}
              suffix="%"
              valueStyle={{ color: '#722ed1' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="请假人数"
              value={7}
              valueStyle={{ color: '#cf1322' }}
            />
          </Card>
        </Col>
      </Row>

      <Row gutter={16}>
        <Col span={24}>
          <Card title="各部门出勤情况" size="small">
            <Table
              dataSource={personnelData}
              columns={[
                { title: '部门', dataIndex: 'department', key: 'department' },
                { title: '总人数', dataIndex: 'total', key: 'total' },
                { title: '在岗', dataIndex: 'present', key: 'present' },
                { title: '缺勤', dataIndex: 'absent', key: 'absent' },
                { 
                  title: '出勤率', 
                  key: 'rate',
                  render: (_, record) => {
                    const rate = ((record.present / record.total) * 100).toFixed(1)
                    return <Progress percent={parseFloat(rate)} size="small" />
                  }
                },
              ]}
              pagination={false}
              size="small"
            />
          </Card>
        </Col>
      </Row>
    </div>
  )

  const renderReportContent = () => {
    switch (reportType) {
      case 'energy':
        return renderEnergyReport()
      case 'parking':
        return renderParkingReport()
      case 'device':
        return renderDeviceReport()
      case 'personnel':
        return renderPersonnelReport()
      default:
        return renderEnergyReport()
    }
  }

  return (
    <Layout>
      <div style={{ padding: '24px' }}>
        <Card 
          title="报表中心"
          extra={
            <Space>
              <Select
                value={reportType}
                onChange={setReportType}
                style={{ width: 120 }}
              >
                <Option value="energy">能耗报表</Option>
                <Option value="parking">停车报表</Option>
                <Option value="device">设备报表</Option>
                <Option value="personnel">人员报表</Option>
              </Select>
              <RangePicker
                value={dateRange}
                onChange={setDateRange}
                style={{ width: 240 }}
              />
              <Button 
                icon={<FileExcelOutlined />}
                onClick={() => handleExport('Excel')}
                loading={loading}
              >
                导出Excel
              </Button>
              <Button 
                icon={<FilePdfOutlined />}
                onClick={() => handleExport('PDF')}
                loading={loading}
              >
                导出PDF
              </Button>
              <Button 
                icon={<PrinterOutlined />}
                onClick={handlePrint}
              >
                打印
              </Button>
            </Space>
          }
        >
          {renderReportContent()}
        </Card>
      </div>
    </Layout>
  )
}

